package com.infoland.afanmall.base.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.view.viewpage.MViewPager;
import com.infoland.afanmall.model.eventBus.main.InternetCloseBus;
import com.infoland.afanmall.model.eventBus.main.RefBus;
import com.infoland.afanmall.model.fuPin.fragment.FuPinFragment;
import com.infoland.afanmall.model.my.fragment.MyCenterFragment;
import com.infoland.afanmall.model.story.fragment.StoryFragment;
import com.infoland.afanmall.model.youXuan.fragment.YouXuanFragment;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxPermissionsTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends AppCompatActivity {
    @BindView(R.id.bottom)
    BottomNavigationViewEx bnve;
    @BindView(R.id.view_page)
    MViewPager viewPage;
    @BindView(R.id.internet_error_layout)
    LinearLayout internetLayout;
    private ArrayList<Fragment> fragments; //fragment 集合
    private VpAdapter adapter;
    private int tabPostion = 1;//按钮位置
    private int pagePostion = 1;//ViewPage位置

    private int getLayout() {
        return R.layout.activity_main;
    }

    // 初始化Fragment
    private void initData() {
        fragments = new ArrayList<>();
        fragments.add(new StoryFragment());//故事
        fragments.add(new YouXuanFragment());//优选
        fragments.add(new FuPinFragment());//扶贫馆
        fragments.add(new MyCenterFragment());//我的
        adapter = new VpAdapter(getSupportFragmentManager(), fragments);
        viewPage.setAdapter(adapter);
        viewPage.setScroll(false); //禁止滑动
        viewPage.setOffscreenPageLimit(2); //设置预加载，最小为2
        viewPage.setCurrentItem(1); //初始滑动位置
        bnve.setCurrentItem(1);//初始点击位置
        bnve.setupWithViewPager(viewPage);
        isInternet();
        addListener();

    }


    // 设置底部样式
    private void setBottomStyle() {
        // 开启或关闭点击动画(文字放大效果和图片移动效果)。 默认为 true.
//        bnve.enableAnimation(false);
        // 开始或关闭导航条位移模式。如果为 true，选中项和其他项的宽度不一样。当菜单数大于3时，默认为 true。
        bnve.enableShiftingMode(false);
        // 开始或关闭子菜单位移模式。 如果为 true，除了当前选中项，其他项的文本将会隐藏。 当菜单数大于3时，默认为 true。
        bnve.enableItemShiftingMode(false);
        bnve.setTextVisibility(true);
//        bnve.getIconAt(0)

//        int iconSize = 23;
        bnve.setIconSize(21, 22);
//        bnve.setTextSize(12);

//        bnve.initialise();//初始化
//        bnve.setBottomNavigationItem(7,21);

        // set item height
//        bnve.setItemHeight(BottomNavigationViewEx.dp2px(this, 50));
        StatusBarKit.immersiveBlackTitleText(this);//沉浸黑字
    }

    //    获取权限
    private void getQuanXian() {
        RxPermissionsTool.
                with(CacheKit.ACTIVITY).
                addPermission(Manifest.permission.CAMERA).
                addPermission(Manifest.permission.ACCESS_FINE_LOCATION).
                addPermission(Manifest.permission.ACCESS_COARSE_LOCATION).
                addPermission(Manifest.permission.READ_EXTERNAL_STORAGE).
                addPermission(Manifest.permission.CALL_PHONE).
                addPermission(Manifest.permission.READ_PHONE_STATE).
                initPermission();
    }

    // 添加监听，初始选中位置
    private void addListener() {
        bnve.setOnHoverListener((v, event) -> {
            return false;
        });
        bnve.setOnNavigationItemSelectedListener(item -> {
            LogKit.E("item ---->   ", "  " + item);
            LogKit.E("setOnNavigationItemSelectedListener ---->   ", "  " + item.getOrder());
            return true;
        });
        viewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                LogKit.E("onPageSelected ---->   ", "  " + position);
//                FragmentManager fragmentManager = fragments.get(position).getFragmentManager();
                switch (position) {
                    case 0:
                        StatusBarKit.immersiveBlackTitleText(MainActivity.this);
//                        StatusBarKit.immersive(MainActivity.this);
                        break;
                    case 1:
                        StatusBarKit.immersive(MainActivity.this);
                        break;
                    case 2:
                        StatusBarKit.immersive(MainActivity.this);
                        break;
                    case 3:
                        StatusBarKit.immersive(MainActivity.this);
                        break;
                }
                pagePostion = position;
                isInternet();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        bnve.getBottomNavigationItemView(0).setOnClickListener(v -> {
            LogKit.E("setOnClickListener ---->   ", "  0");
            setItem(0);
        });
        bnve.getBottomNavigationItemView(1).setOnClickListener(v -> {
            LogKit.E("setOnClickListener ---->   ", "  1");
            setItem(1);
        });
        bnve.getBottomNavigationItemView(2).setOnClickListener(v -> {
            setItem(2);
        });
        bnve.getBottomNavigationItemView(3).setOnClickListener(v -> {
            setItem(3);
        });
    }

    //检查网络
    private void isInternet() {
        if (ToolsKit.isInternet()) {
            closeErrorInternetView();
        } else {
            showErrorInternetView();
        }
    }

    // tab 点击 事件
    private void setItem(int i) {
        tabPostion = i;
        //        执行刷新
        if (tabPostion == pagePostion) {
            bnve.setCurrentItem(i);
            viewPage.setCurrentItem(i);
            startRefresh(i);
        }
        //        不执行操作
        else {
            bnve.setCurrentItem(i);
            viewPage.setCurrentItem(i);
        }

    }

    //刷新对应的Fragment
    private void startRefresh(int i) {
        ToastUtils.showShort("开始刷新第" + i + " 页");
    }

    //展示没有网界面
    private void showErrorInternetView() {
        ToolsKit.hideView(viewPage);
        ToolsKit.showView(internetLayout);
        StatusBarKit.immersiveBlackTitleText(MainActivity.this);
    }

    //展示正常界面
    private void closeErrorInternetView() {
        ToolsKit.hideView(internetLayout);
        ToolsKit.showView(viewPage);
        if (pagePostion == 0) {
            StatusBarKit.immersiveBlackTitleText(MainActivity.this);
        } else {
            StatusBarKit.immersive(MainActivity.this);
        }
    }

    @OnClick(R.id.internet_button)
    public void onViewClicked() {
        LogKit.E("internet_error_layout ---->   ", "  " + tabPostion);
        if (RxNetTool.isAvailable(CacheKit.APP_CONTEXT)) {
            closeErrorInternetView();
            ToolsKit.sendMessage(new RefBus().setFragmentId(tabPostion));
        } else {
            LogKit.E("internet_error_layout ---->   ", "  当前没有网络");
            ToastUtils.showShort("对不起，当前网络不可用");
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setEnterTransition(new Fade());
        setContentView(getLayout());
        ButterKnife.bind(this);
//        EventBus.getDefault().register(MainActivity.this);
        ToolsKit.registered(MainActivity.this);
        setBottomStyle();
        initData();
    }

    // PageAdapter
    private static class VpAdapter extends FragmentPagerAdapter {
        private List<Fragment> data;

        public VpAdapter(FragmentManager fm, List<Fragment> data) {
            super(fm);
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Fragment getItem(int position) {
            return data.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //如果注释这行，那么不管怎么切换，page都不会被销毁
            //super.destroyItem(container, position, object);
        }
    }

    //    接收返回的,requestCode
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogKit.E(" resultCode  ", "  " + resultCode);
        LogKit.E(" requestCode  ", "  " + requestCode);
        /*** 从我的订单--->优选界面**/
        if (resultCode == CONST.RESULT_ORDER_TO_YOU_XUAN) {
            setItem(1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToolsKit.unregister(MainActivity.this);
    }

    //接收网络连接中断
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Message(InternetCloseBus c) {
        showErrorInternetView();
    }


    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
            ToastUtils.cancel();
            ToolsKit.backHome(this);
        } else {
            TOUCH_TIME = System.currentTimeMillis();
            ToastUtils.showShort("双击退出" + this.getApplicationContext().getString(R.string.app_name));
        }
    }
}
